﻿using System;
using System.Data.Entity;
using System.Globalization;
using System.Web.Mvc;
using System.Linq;
using Newtonsoft.Json;
using QDT.Common;
using QDT.Core.Deals;
using QDT.Core.Members;
using QDT.Core.Projects;
using QDT.MVC.Security;
using QDT.Services.Credits;
using QDT.Services.Deals;
using QDT.Services.DTO.Project;
using QDT.Services.Members;
using QDT.Services.Projects;
using QDT.Web.Code;
using QDT.Web.Models;

namespace QDT.Web.Controllers
{
    public class ProjectController : BaseController
    {
        private readonly IDealService _dealService;
        private readonly IUserService _userService;
        private readonly ICreditService _creditService;
        private readonly IProjectService _projectService;
        private const int ProjectFlag = 870;

        public ProjectController(IDealService dealService, IUserService userService, ICreditService creditService, IProjectService projectService)
        {
            _dealService = dealService;
            _userService = userService;
            _creditService = creditService;
            _projectService = projectService;
        }

        public ActionResult Index(int id)
        {
            var project = _projectService.GetProject(id);
            if (project == null) return NotFound();
            if (!project.IsEffect || project.IsDelete) return NotFound();

            ViewBag.LoanInfo = JsonConvert.DeserializeObject<LoanInfo>(string.IsNullOrEmpty(project.Parent.LoanInfo) ? "" : project.Parent.LoanInfo);
            ViewBag.ProjectProcess = JsonConvert.DeserializeObject<ProjectProcess>(string.IsNullOrEmpty(project.Parent.ProjectProcess) ? "" : project.Parent.ProjectProcess);
            ViewBag.RiskControl = JsonConvert.DeserializeObject<RiskControl>(string.IsNullOrEmpty(project.Parent.RiskControl) ? "" : project.Parent.RiskControl);

            return View(project);
        }

        [HttpPost]
        [DefaultAuthorize]
        public ActionResult Bid(int id, decimal money, string safePassword)
        {
            if (money % 1 != 0)
            {
                return Error("投资金额需要填入正整数！");
            }

            var user = QDTContext.Current.User;

            if (user.GroupID != 3)
            {
                return Error("安全密码错误");
            }

            try
            {
                _dealService.Bid(user.ID, id, money);
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

            return RedirectToAction("BidSuccess", new { projectId = id, loadMoney = money });
        }

        [DefaultAuthorize]
        public ActionResult BidSuccess(int projectId, decimal loadMoney)
        {

            if (!QDTContext.Current.IsAuthenticated) return HttpNotFound();
            var user = QDTContext.Current.User;

            ViewData["Jump"] = Url.Action("Index", "User");

            ViewBag.ProjectId = projectId.ToString(CultureInfo.InvariantCulture);
            ViewBag.LoadMoney = loadMoney.ToString(CultureInfo.InvariantCulture);
            ViewBag.OrderNum = new Random().Next(1000, 9999).ToString(CultureInfo.InvariantCulture);

            return View(user);
        }

        [OutputCache(Duration = 30)]
        public ActionResult BidList(int projectid)
        {
            ViewData["Project"] = DbProvider.GetByID<Project>(projectid);
            var credits = _creditService.GetCreditPaged(null, null, projectid);
            return PartialView(credits.ToList());
        }

        [OutputCache(Duration = 30)]
        public ActionResult AllBidList(int projectid)
        {
            var credits = _creditService.GetCreditList(null, projectid, null);
            return PartialView(credits);
        }

        [OutputCache(Duration = 30)]
        public ActionResult RepayList(int projectid, bool isAgree = false)
        {
            var list = IoC.Resolve<IDealService>().GetRepaymentScheme(projectid);
            if (isAgree)
            {
                return PartialView("_agreeRepayList", list);
            }
            return PartialView(list);
        }

        public ActionResult BorrowerSta(int userId)
        {
            var user = _userService.GetUserByID(userId);
            user.UserSta = _userService.UserSta(user.UserName);
            return PartialView(user);
        }

        [OutputCache(Duration = 30)]
        public ActionResult Agreement(int id)
        {
            var project = DbProvider.GetByID<Project>(id);
            if (project.Status != ProjectStatus.Repaying && project.Status != ProjectStatus.Repaid)
            {
                return JavaScript("协议未生成");
            }
            if (!string.IsNullOrWhiteSpace(project.AgreementLink))
            {
                Response.ContentType = "application/pdf";
                Response.WriteFile(project.AgreementLink);
                Response.End();
                return null;
            }
            var credits = DbProvider.D<Credit>().Where(x => x.ProjectID == id && x.AssignmentID == 0).ToList();

            if (project.ID <= 638) return View(new AgreementModel(project, credits));
            if (project.TypeID == 9) return View("dengshengxin", new AgreementModel(project, credits));
            if (project.TypeID != 3) return View("_newAgreement", new AgreementModel(project, credits));
            var agree = new AgreementModel(project, credits)
            {
                Agency = DbProvider.D<ProjectAgency>().FirstOrDefault(x => x.ID == project.Parent.AgencyId)
            };
            return View("_DaiBaoAgreement", agree);
        }

        [OutputCache(Duration = 30)]
        public ActionResult WebAgreement(int id)
        {
            var project = DbProvider.GetByID<Project>(id);
            if (project.Status != ProjectStatus.Repaying && project.Status != ProjectStatus.Repaid)
            {
                return JavaScript("协议未生成");
            }
            var credits = DbProvider.D<Credit>().Where(x => x.ProjectID == id && x.AssignmentID == 0).ToList();

            if (project.ID <= 638) return View("Agreement", new AgreementModel(project, credits));
            if (project.TypeID == 9) return View("dengshengxin", new AgreementModel(project, credits));
            if (project.TypeID != 3) return View("_newAgreement", new AgreementModel(project, credits));
            var agree = new AgreementModel(project, credits)
            {
                Agency = DbProvider.D<ProjectAgency>().FirstOrDefault(x => x.ID == project.Parent.AgencyId)
            };
            return View("_DaiBaoAgreement", agree);
        }

        [OutputCache(Duration = 30)]
        public ActionResult CompanyInfo(int projectId)
        {
            var project = DbProvider.GetByID<Project>(projectId);
            var feild = DbProvider.D<ProjectFeild>().Where(x => x.TypeID == project.TypeID).ToList();
            ViewData["Feilds"] = feild;
            return PartialView(project);
        }

        [ChildActionOnly]
        [OutputCache(Duration = 30)]
        public PartialViewResult OtherFile(int projectId)
        {
            var images = _projectService.GetProjectImages(projectId);
            ViewBag.ProjectId = projectId;
            return PartialView(images);
        }

        [DefaultAuthorize]
        public ActionResult UserBalance()
        {
            var user =
                DbProvider.D<User>().Include(x => x.UserAccount).FirstOrDefault(x => x.UserName == User.Identity.Name);
            return PartialView("_userBalance", user);
        }

        [OutputCache(Duration = 30)]
        public ActionResult PojectInfo(int id)
        {
            var project = DbProvider.GetByID<Project>(id);
            return PartialView("_pojectInfo", project);
        }
    }
}
